package com.weapons.week0903_weapons.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 *
 * Created by Administrator on 2016/7/4.
 */
public class NetUtils {
    public static byte[] getDataByBytes(String url){
        try {
            HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
            if(con.getResponseCode() == 200){
                InputStream is = con.getInputStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                int n = -1;
                byte[] buf = new byte[1024*8];
                while((n = is.read(buf)) != -1){
                    baos.write(buf,0,n);
                }
                return baos.toByteArray();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static String getDataByString(String url){
        try {
            HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
            if(con.getResponseCode() == 200){
                InputStream is = con.getInputStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                int n = -1;
                byte[] buf = new byte[1024*8];
                while((n = is.read(buf)) != -1){
                    baos.write(buf,0,n);
                }
                return baos.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
